import React, { Component } from 'react';
import TodoButton from './TodoButton/TodoButton';
import TodoList from './TodoList';
import '../assets/css/todo.css';

export default class Todo extends Component {
  state = {
    todoList: [],
    text: ''
  }
  constructor() {
    super()
    this.myRef = React.createRef();
  }
  onTodoTextChange = (e) => {
    this.setState({
      text: e.target.value
    })
  }

  onAddTodo = () => {
    // console.log('新增');
    const todo = {
      id: Date.now(),
      text: this.state.text
    }
    this.setState({
      todoList: [...this.state.todoList, todo],
      text: ''
    })
  }

  delTodo = (id) => {
    const newTodoList = this.state.todoList.filter(item => item.id != id)
    this.setState({
      todoList: newTodoList
    })
  }

  componentDidMount() {
    // 必须通过 current 获取节点
    this.myRef.current.focus();
  }

  render() {
    const { text, todoList } = this.state

    return (
      <div className='todo'>
        {/* 输入框部分 */}
        <div className='todo-form'>
          <input ref={this.myRef} className='todo-input' type="text" placeholder='请输入待办事项' value={text} onChange={this.onTodoTextChange} />
          {/* <TodoButton>新增</TodoButton> */}
          <TodoButton type="primary" onClick={this.onAddTodo}>新增</TodoButton>
        </div>

        <TodoList
          data={todoList}
          right={(item) => <TodoButton onClick={() => this.delTodo(item.id)}>删除</TodoButton>}>
        </TodoList>
      </div >
    )
  }
}
